package p.sunmes.les.listener;

import java.util.ArrayList;
import java.util.List;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;

import p.sunmes.les.action.CallAction;
import p.sunmes.les.action.PlaySoundEffectAction;

public class ColorChangeTouchListener extends InputListener {

	private String btnSoundPath;

	private CallAction callAction;
	float touchX;

	private List<Actor> effectTargets = new ArrayList<Actor>();

	public List<Actor> getEffectTargets() {
		return effectTargets;
	}

	public void addEffectTargets(Actor... actors) {
		if (actors == null) {
			return;
		}
		for (Actor actor : actors) {
			effectTargets.add(actor);
		}
	}

	public ColorChangeTouchListener(CallAction action) {
		callAction = action;
	}

	public ColorChangeTouchListener(CallAction action, String sound) {
		callAction = action;
		btnSoundPath = sound;
	}

	@Override
	public boolean touchDown(InputEvent event, float x, float y, int pointer,
			int button) {
		if (pointer != 0) {
			return false;
		}
		//		System.out.println("Pointer" + pointer + "  button:" + button);
		touchX = event.getStageX();
		if (event.getTarget().getActions().size > 0) {
			return false;
		}
		event.getTarget().clearActions();
		event.getTarget().addAction(Actions.color(Color.GRAY));
		effectTargetsColorAction(Color.GRAY);
		return true;
	}

	public void touchUp(InputEvent event, float x, float y, int pointer,
			int button) {
		if (pointer != 0) {
			return;
		}
		event.getTarget().clearActions();
		clearEffectTargetsAction();
		//		System.out.println(event.getStageX() - touchX);
		if (Math.abs(event.getStageX() - touchX) > 20) {
			event.getTarget().addAction(Actions.color(Color.WHITE));
			effectTargetsColorAction(Color.WHITE);
			return;
		}
		if (event.getTarget().hit(x, y, true) != null) {
			if (btnSoundPath != null && !btnSoundPath.isEmpty()) {
				event.getTarget()
						.addAction(Actions.sequence(Actions.color(Color.WHITE),
								PlaySoundEffectAction.create(btnSoundPath),
								callAction));
				effectTargetsColorAction(Color.WHITE);
			} else {
				event.getTarget().addAction(Actions
						.sequence(Actions.color(Color.WHITE), callAction));
				effectTargetsColorAction(Color.WHITE);
			}

		} else {
			event.getTarget().addAction(Actions.color(Color.WHITE));
			effectTargetsColorAction(Color.WHITE);
		}
	};

	public void effectTargetsColorAction(Color color) {
		for (Actor et : effectTargets) {
			et.addAction(Actions.color(color));
		}
	}

	public void clearEffectTargetsAction() {
		for (Actor et : effectTargets) {
			et.clearActions();
		}
	}

}
